#include "bmp_dir.h"

int bmp_files_size;

// 初始化数组
void initList()
{
    bmp_files_size = 0;
    BmpFile *bmp_files = (BmpFile *)malloc(sizeof(BmpFile *));
}

// 将指定的.bmp文件添加到数组中
int addBmpFileToArray(const char *dirname, const char *filename)
{
    // 重新分配内存以添加新元素
    bmp_files[bmp_files_size] = (BmpFile *)malloc(sizeof(BmpFile));
    if (bmp_files[bmp_files_size] == NULL)
    {
        perror("Memory allocation failed");
        free(bmp_files[bmp_files_size]);
        return -1;
    }
    // strcat(filename,"\0");
    snprintf(bmp_files[bmp_files_size]->filename, 256, "%s/%s", dirname, filename);
    bmp_files_size++;
    return 0;
}

// 打印数组中的所有文件名
void printBmpFiles()
{
    for (int i = 0; i < bmp_files_size; i++)
    {
        printf("%s\n", bmp_files[i]->filename);
    }
}

// 清理数组
void freeBmpFilesArray()
{
    for (size_t i = 0; i < bmp_files_size; i++)
    {
        free(bmp_files[i]);
    }
}

// 将对应目录下的BMP图片名存数组中
int bmp_arr(char *dirname)
{
    initList();

    // 将dirname拼接成./res/user/dirname再传入函数
    char *dir = NULL;
    char *userdir = "./res/user/";
    dir = (char *)malloc((strlen(userdir) + strlen(dirname) + 2) * sizeof(char));

    // 拼接用户目录路径
    strcpy(dir, userdir);
    // strcat(dir, "/");
    strcat(dir, dirname);

    if (addBmpFilesToListToArray(dir) != 0)
    {
        return -1;
    }

    printBmpFiles();

    free(dir);

    return 0;
}

// 遍历目录添加文件名到数组
int addBmpFilesToListToArray(const char *dirname)
{
    // printf("dirname: %s\n", dirname);
    DIR *dir = opendir(dirname);
    if (dir == NULL)
    {
        perror("opendir");
        return -1;
    }
    while (1)
    {
        struct dirent *entry = readdir(dir);
        if (entry == NULL)
        {
            break;
        }
        // 判断文件名是否包含.bmp
        if (entry->d_type == DT_REG && strstr(entry->d_name, ".bmp") != NULL)
        {
            // 添加文件名到数组
            if (addBmpFileToArray(dirname, entry->d_name) != 0)
            {
                closedir(dir);
                return -1;
            }
        }
    }
    closedir(dir);
    return 0;
}

// 删除数组中指定下标的文件名
int removeBmpFileFromArray(int index)
{
    if (index < 0 || index > bmp_files_size)// 检查索引是否越界
    {
        fprintf(stderr, "Index out of bounds\n");
        return -1;
    }
    // 释放指定下标的内存
    free(bmp_files[index]);
    // 将后面的元素向前移动
    for (int i = index; i < bmp_files_size - 1; i++)
    {
        bmp_files[i] = bmp_files[i + 1];
    }
    bmp_files_size--; // 更新数组大小
    return 0;
}